from concurrent.futures import ThreadPoolExecutor

import tornado.ioloop
import tornado.web
import router
from config import config
import gc

#入口文件
from services import MyCache
from utils import TimerUtils
settings = {
    'template_path': 'views',
    'static_path': 'static',
    'static_url_prefix': '/static/',
    "cookie_secret" : "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
    "xsrf_cookies": False,
    'debug' : False,

}

import uvloop
import asyncio

from tornado.platform.asyncio import BaseAsyncIOLoop


class TornadoUvloop(BaseAsyncIOLoop):

    def initialize(self, **kwargs):
        loop = uvloop.new_event_loop()
        try:
            super(TornadoUvloop, self).initialize(
                loop, close_loop=True, **kwargs)
        except Exception:
            loop.close()
            raise

@TimerUtils.delayed(60*60*24)
def clear():
    cache = MyCache()
    cache.session().expire()
    cache.fsession().expire()
    gc.collect()


def main():
    clear()
    exe = ThreadPoolExecutor(10)
    asyncio.get_event_loop().set_default_executor(exe)
    application = tornado.web.Application(
        router.Url,
        **settings,)
    application.listen(config["port"],xheaders=True)
    tornado.ioloop.IOLoop.configure(TornadoUvloop)
    tornado.ioloop.IOLoop.instance().start()

def mainPool():
    clear()
    exe = ThreadPoolExecutor(20)
    asyncio.get_event_loop().set_default_executor(exe)
    application = tornado.web.Application(
        router.Url,
        **settings,)
    application.listen(config["port"],xheaders=True)
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.start(4)
    tornado.ioloop.IOLoop.configure(TornadoUvloop)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()
